import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:hxdj/common/base_page/base_page.dart';
import 'package:hxdj/common/components/my_alert.dart';
import 'package:hxdj/common/dio/dio_http.dart';
import 'package:hxdj/common/my_global.dart';
import 'package:hxdj/common/my_pay_manager.dart';
import 'package:hxdj/home/address/select_address/address_model.dart';
import 'package:hxdj/home/home_viewmodel.dart';
import 'package:hxdj/home/order/order_manager.dart';
import 'package:hxdj/home/project_details/project_details_viewmodel.dart';
import 'package:hxdj/home/select_service_time/select_service_time_page.dart';
import 'package:hxdj/home/technician_detail.dart/technician_detail_viewmodel.dart';
import 'package:hxdj/login/user_model.dart';
import 'package:hxdj/mine/pay/select_pay.dart';
import 'package:provider/provider.dart';

class OrderCreateViewModel extends BaseViewModel {
  //项目详情
  late ProjectDetailsModel detailModel;

  //选择地址
  AddressModel? addressModel;

  //选择服务人员
  NearbyTechnicianModel? technicianModel;

  //选择服务时间
  late String serviceTime = "";

  //预估路费
  late String roadFee = "";

  //总路费
  late String totalFee = "";

  //创建订单, 如果先选择项目, 就没有Tid. 如果是技师详情进入的就是有Tid
  late String tId = "";
  late String gId = "";

  @override
  requestData({Function(dynamic)? onSuccess, Function(dynamic)? onError}) async {
    setState(ViewState.loading);

    if (tId.isNotEmpty) {
      // 去请求服务器数据. 技师详情
      await requestTechnicianInfo(tId);
    } else {
      // 去请求服务器数据.
      await Future.delayed(const Duration(microseconds: 200));
    }
    totalFee = detailModel.price ?? "";
    // 更新页面.
    setState(ViewState.normal);
  }

  //请求当前及时详情
  requestTechnicianInfo(String tId) async {
    Map<String, dynamic> resultMap =
        await DioHttpManager().request(MyApi.technicianInfo, method: DioHttpManager.post, data: {"t_id": tId});
    if (resultMap["code"] == 0) {
      // 请求成功.
      TechnicianDetailModel detailModel = TechnicianDetailModel.fromMap(resultMap["data"]);

      //为创建订单做数据准备
      Map<String, dynamic> technicianMap = {
        "t_id": detailModel.tId,
        "m_id": detailModel.mId,
        "name": detailModel.name,
        "sex": detailModel.sex,
        "logo": detailModel.headPortrait,
        "id": detailModel.id,
      };

      technicianModel = NearbyTechnicianModel.fromMap(technicianMap);
    }
  }

  selectServiceAddress(AddressModel model) {
    addressModel = model;
    notifyListeners();
    calculateRoadFee();
  }

  selectServiceTechnician(NearbyTechnicianModel model) {
    technicianModel = model;
    notifyListeners();
    calculateRoadFee();

  }

  //选择服务时间
  selectServiceTime() {
    //选择服务时间
    onSelectCallback(value) {
      debugPrint("object $value");
      serviceTime = value;
      notifyListeners();
      //计算路费
      calculateRoadFee();
    }

    MyAlertManager.sheetAlert(AlertType.customWidget, context, "", "",
        child: SelectServiceTimePage(object: {
          "onSelectCallback": onSelectCallback,
          "tId": technicianModel!.tId.toString(),
          "serviceTime": serviceTime
        }));
  }

  //开始支付
  startSelectPay(String price) {
    // //选择了那个支付方式, 传一个闭包过去
    Future<void> onSelectCallback(String value) async {
      if (value == "ic_wechat_pay") {
        //微信支付
        createOrderPayParams(price, 1);
      } else if (value == "ic_ali_pay") {
        //支付宝支付
        createOrderPayParams(price, 2);
      } else {
        //其他支付方式
        debugPrint("object $value");
      }
    }

    //查看 当前支付的支持那种方式
    Map<String, dynamic> paramsObjectMap = {"price": price, "onSelectCallback": onSelectCallback};
    MyAlertManager.sheetAlert(AlertType.customWidget, context, "", "", child: SelectPayPage(object: paramsObjectMap));
  }

  //请求相关的支付参数,创建订单
  createOrderPayParams(String price, int payType) async {
    // 去请求服务器数据. 下订单
    Map<String, dynamic> paramsMap = {
      "service_time": serviceTime,
      "adds_id": addressModel?.id,
      "contacts": addressModel?.contacts ?? "",
      "mobile": addressModel?.mobile,
      "pay_num": "1",
      "t_id": technicianModel?.tId,
      "sex": addressModel?.sex,
      "travel_mode": "2", //出行方式 1 公交/地铁 2 打车/出租
      "pay_type": payType, //支付方式 1 微信 2 支付宝
      "goods_id": gId.isNotEmpty ? gId : "0",
      "template_id": tId,
      "m_id": technicianModel?.mId.toString(), //用户ID
    };


    Map<String, dynamic> resultMap =
        await DioHttpManager().request(MyApi.anmoV2CreateOrder, method: DioHttpManager.post, data: paramsMap);

    if (resultMap['code'] == 0) {
      //查看 当前支付的支持那种方式
      Map<String, dynamic> resultPayManagerMap = resultMap["data"];

      String aliPayUrl = resultPayManagerMap['pay_url'];
      String orderId = resultPayManagerMap['order_id'].toString();

      Map<String, dynamic> weixinUrlMap = resultPayManagerMap['weixin_url'];

      //去支付
      switch (payType) {
        case 2:
          {
            OrderManager.goAliPay(aliPayUrl, orderId, context);
          }

          break;
        case 1:
          {
            MyPayManager().goWechatPay(weixinUrlMap, (p0) {});
          }

          break;
        default:
      }

      //刷新首页的订单数据
      HomeViewModel homeViewModel = Provider.of<HomeViewModel>(context, listen: false);
      homeViewModel.reloadOrderData();
    } else {
      EasyLoading.showToast(resultMap["msg"]);
    }
  }

  //预计路费的计算
  calculateRoadFee() async {
    if (serviceTime.isNotEmpty && addressModel != null) {
      MyGlobalViewModel globalViewModel = MyGlobalViewModel.getGlobalViewModel(context);
      UserModel? userModel = globalViewModel.userModel;
      Map<String, dynamic> params = {
        "t_id": technicianModel?.tId,
        "adds_id": addressModel?.id,
        "order_id": 0,
        "template_id": detailModel.templateId,
        "adds_city": addressModel?.addsCity,
        "member_id": userModel?.memberId,
        "adds_province": addressModel?.addsProvince,
        "service_time": serviceTime,
        "default_mode": "6" //5、公交/地铁 6、打车/出租
      };

      Map<String, dynamic> resultMap = await DioHttpManager()
          .request(MyApi.calculateFare, method: DioHttpManager.post, data: params, isLoading: true);

      if (resultMap['code'] == 0) {
        roadFee = resultMap["data"]["fare"].toString();
      } else {
        EasyLoading.showToast(resultMap["msg"]);
      }
      totalFee = (num.parse(roadFee) + num.parse(detailModel.price!)).toStringAsFixed(2).toString();

      notifyListeners();
    }
  }

  void clean() {
    addressModel = null;
    serviceTime = "";
    roadFee = "";
    technicianModel = null;
    notifyListeners();
  }
}
